<template>
  <div class="loginContainer">
    <Header></Header>
    <div class="imgbox">
      <van-image
        width="200"
        height="100"
        margin-left="100"
        src="//yanxuan.nosdn.127.net/39c5e4583753d4c3cb868a64c2c109ea.png"
      />
    </div>
    <van-form>
      <van-field
        v-model="phone"
        name="phone"
        label="手机号"
        placeholder="请输入您的手机号"
        :rules="telRules"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请输入正确的密码' }]"
      />
      <span class="go"
        >没有账号？去 <a @click="toRegister" target="_blank">注册</a>
      </span>
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          @click.prevent="userLogin"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { Dialog } from 'vant';
export default {
  name: 'Login',
  data() {
    return {
      phone: '',
      password: '',
      telRules: [
        {
          required: true,
          message: '手机号码不能为空',
          trigger: 'onBlur',
        },
        {
          // 自定义校验规则
          validator: value => {
            return /^1[3-9]\d{9}$/.test(value);
          },
          message: '请输入正确格式的手机号码',
          trigger: 'onBlur',
        },
      ],
    };
  },
  methods: {
    //点击去主页
    toHome() {
      this.$router.push('/home');
    },
    //点击去注册页
    toRegister() {
      this.$router.push('/register');
    },
    //点击去搜索页
    toSearch() {
      this.$router.push('/search');
    },
    //点击去购物车
    toCart() {
      this.$router.push('/cart');
    },
    //点击登录，去到个人中心页
    async userLogin() {
      try {
        const { phone, password } = this;
        const result = await this.$store.dispatch('userLogin', {
          phone,
          password,
        });
        //如果登录成功的话，弹框登录成功，准备跳转到个人中心页面
        Dialog({ message: '登录成功，前往个人中心页面' });
        // let redirect = this.$route.query.redirect || '/'
        this.$router.push('center');
      } catch (error) {
        Dialog({ message: '登录失败，请检查账号密码重新登录' });
      }
    },
  },
};
</script>

<style lang="less" scoped>
.loginContainer {
  .imgbox {
    width: 375px;
    height: 100px;
    padding: 50px 50px;
    margin-left: 40px;
    margin-top: 46px;
  }
  .go {
    font-size: 15px;
    display: flex;
    justify-content: center;
    a {
      color: #e1251b;
    }
  }
}
</style>
